package org.emet.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.emet.Constants;
import org.emet.dao.CremationHistDao;
import org.emet.dao.CrematorDao;
import org.emet.entity.biz.CremationHist;
import org.emet.entity.biz.Cremator;
import org.emet.jee.BusinessException;
import org.emet.jee.core.dao.Page;
import org.emet.service.dto.CremationHistCriteria;
import org.emet.service.dto.CremationHistDisplayItem;
import org.emet.service.dto.DatePair;
import org.hibernate.ObjectNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.flex.remoting.RemotingDestination;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

@Service
@Transactional
@RemotingDestination
public class CremationHistService {
	@Autowired
	private CremationHistDao cremationHistDao;
	@Autowired
	private CrematorDao crematorDao;
	@Autowired
	private CrematorService crematorService;

	private static Logger logger = LoggerFactory.getLogger(CremationHistService.class);

	public void save(CremationHist entity) {
		try {
			Cremator cremator = crematorDao.get(entity.getCrematorId());
			Assert.isTrue(!cremator.getStatus().equals(Constants.STATUS_INVALID + ""), "火化炉当前不可用！");
			if (entity.getStartDate() != null && entity.getEndDate() == null) {
				cremator.setStatus(Constants.STATUS_BUSY + "");
			} else if (entity.getStartDate() != null && entity.getEndDate() != null) {
				cremator.setStatus(Constants.STATUS_OK + "");
			}
			entity.getRegistration().setCremationDate(entity.getStartDate());
			cremationHistDao.save(entity);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BusinessException("发生异常!");
		}
	}

	@Transactional(readOnly = true)
	public CremationHist get(Long id) {
		try {
			CremationHist cremationHist = cremationHistDao.get(id);
			CremationHist target = new CremationHist();
			BeanUtils.copyProperties(cremationHist, target);
			return target;
		} catch (ObjectNotFoundException e) {
			logger.error(e.getMessage(), e);
			throw new BusinessException("发生异常!");
		}
	}

	public void del(Long... ids) {
		for (Long id : ids) {
			if (notExist(id)) {
				continue;
			}
			try {
				cremationHistDao.delete(id);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				throw new BusinessException("发生异常!");
			}
		}
	}

	private boolean notExist(Long id) {
		return get(id) == null;
	}

	@Transactional(readOnly = true)
	public Page<CremationHist> search(Page<CremationHist> page, CremationHistCriteria criteria) {
		try {
			return cremationHistDao.search(page, criteria);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BusinessException("发生异常!");
		}
	}

	@Transactional(readOnly = true)
	public List<List<CremationHist>> searchByDate(Date start, Date end) {
		try {
			List<CremationHist> result = cremationHistDao.search(start, end);
			List<Cremator> all = crematorDao.getAll();
			ArrayList<List<CremationHist>> resultbyrow = new ArrayList<List<CremationHist>>(all.size());
			for (Cremator cremator : all) {
				ArrayList<CremationHist> row = new ArrayList<CremationHist>(24);
				for (CremationHist hist : result) {
					if (cremator.getName().equals(hist.getCrematorName())) {
						row.add(hist);
					}
				}
				resultbyrow.add(row);
			}
			return resultbyrow;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BusinessException("发生异常!");
		}
	}

	@Transactional(readOnly = true)
	public List<DatePair> getIdelTimeRange(Long id, Long crematorId) {
		try {
			return cremationHistDao.getIdleTimeRange(id, crematorId);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BusinessException("发生异常!");
		}
	}

	@Transactional(readOnly = true)
	public List<Date> getPreorderedTime(Long crematorId, Date date) {
		try {
			return cremationHistDao.getPreorderedTime(crematorId, date);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BusinessException("发生异常!");
		}
	}

	//开始火化
	public Date startCremation(Long histId, Long crematorId) {
		crematorService.endAllBusy(crematorId);
		Date startDate = new Date();
		CremationHist cremationHist = cremationHistDao.get(histId);
		cremationHist.setStartDate(startDate);

		Cremator cremator = crematorDao.get(crematorId);
		Assert.isTrue(!cremator.getStatus().equals(Constants.STATUS_INVALID + ""), "火化炉当前不可用！");
		if (cremationHist.getStartDate() != null && cremationHist.getEndDate() == null) {
			cremator.setStatus(Constants.STATUS_BUSY + "");
		}
		return startDate;
	}

	//结束火化
	public Date endCremation(Long histId, Long crematorId) {
		crematorService.endAllBusy(crematorId);
		Date endDate = new Date();
		CremationHist cremationHist = cremationHistDao.get(histId);
		cremationHist.setEndDate(endDate);

		Cremator cremator = crematorDao.get(crematorId);
		Assert.isTrue(!cremator.getStatus().equals(Constants.STATUS_INVALID + ""), "火化炉当前不可用！");
		if (cremationHist.getStartDate() != null && cremationHist.getEndDate() != null) {
			cremator.setStatus(Constants.STATUS_OK + "");
		}
		return endDate;
	}

	public List<CremationHistDisplayItem> findApprove() {
		try {
			List<CremationHist> result = cremationHistDao.findApprove();
			List<CremationHistDisplayItem> list2 = new ArrayList<CremationHistDisplayItem>(result.size());
			SimpleDateFormat sf = new SimpleDateFormat("HH:mm");
			for (CremationHist cremationHist : result) {
				CremationHistDisplayItem item = new CremationHistDisplayItem(cremationHist.getCrematorName(),
						sf.format(cremationHist.getPreStartDate()), cremationHist.getRegistration().getDeadName());
				list2.add(item);
			}
			return list2;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BusinessException("发生异常!");
		}
	}

	//Report
	@Transactional(readOnly = true)
	public List<Map<String, Object>> searchByYear(int startYear, int endYear, boolean groupByName) {
		try {
			return cremationHistDao.searchByYear(startYear, endYear, groupByName);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BusinessException("发生异常!");
		}
	}

	@Transactional(readOnly = true)
	public List<Map<String, Object>> searchByMon(int startYear, int startMon, int endYear, int endMon,
			boolean groupByName) {
		try {
			return cremationHistDao.searchByMon(startYear, startMon, endYear, endMon, groupByName);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BusinessException("发生异常!");
		}
	}

	@Transactional(readOnly = true)
	public List<Map<String, Object>> searchByDate(Date startDate, Date endDate, boolean groupByName) {
		try {
			return cremationHistDao.searchByDate(startDate, endDate, groupByName);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BusinessException("发生异常!");
		}
	}
}
